package sdk

import (
	"fmt"
	"sync"
)

/*data structure
| msgID
| server | [] [] [] [] [] [] [] [] |
*/
//网关的消息路由过滤规则

type serverMap map[string]*RouteRule

var (
	msgIdRuleMap = make(map[int32]serverMap)
	msgNameRuleMap = make(map[string]serverMap)
	mutex        sync.RWMutex
)

//获取路由规则
func getRouteRuleByName(msgName string) serverMap {

	mutex.RLock()
	defer mutex.RUnlock()

	if rule, ok := msgNameRuleMap[msgName]; ok {
		return rule
	}

	return nil
}

//获取路由规则
func getRouteRule(msgId int32) serverMap {

	mutex.RLock()
	defer mutex.RUnlock()

	if rule, ok := msgIdRuleMap[msgId]; ok {
		return rule
	}

	return nil
}

//注册路由规则
func registerRouteRule(rule *RouteTable) {

	mutex.Lock()

	for _, v := range rule.Rule {
		m, ok := msgIdRuleMap[v.MsgID]
		if !ok {
			m = make(serverMap)
		}

		if _, ok := m[v.ServerName]; !ok {
			m[v.ServerName] = v
		} else {
			panic(fmt.Sprintf("duplicated msg resiger, rule: %+v", rule))
		}

		msgIdRuleMap[v.MsgID] = m
	}

	for _, v := range rule.Rule {
		m, ok := msgNameRuleMap[v.MsgName]
		if !ok {
			m = make(serverMap)
		}

		if _, ok := m[v.ServerName]; !ok {
			m[v.ServerName] = v
		} else {
			panic(fmt.Sprintf("duplicated msg resiger, rule: %+v", rule))
		}

		msgNameRuleMap[v.MsgName] = m
	}
	mutex.Unlock()
}
